package cn.czg.cms.service.impl;


import cn.czg.cms.entity.User;
import cn.czg.cms.mapper.UserMapper;
import cn.czg.cms.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;

    public UserServiceImpl(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public User getById(Long id) {
        return userMapper.selectById(id);
    }

    @Override
    public User getByUsername(String username) {
        return userMapper.selectOne(new QueryWrapper<User>().eq("username", username));
    }

    @Override
    public boolean register(String username, String password, String nickname) {
        if (getByUsername(username) != null) return false;

        User user = new User();
        user.setUsername(username);
        user.setPhone(username);
        user.setPasswordHash(BCrypt.hashpw(password, BCrypt.gensalt()));
        user.setNickname(nickname);
        user.setCreatedAt(LocalDateTime.now());

        return userMapper.insert(user) > 0;
    }

    @Override
    public User login(String username, String password) {
        User user = getByUsername(username);
        if (user == null) return null;

        if (BCrypt.checkpw(password, user.getPasswordHash())) {
            user.setLastLoginAt(LocalDateTime.now());
            userMapper.updateById(user);
            return user;
        }
        return null;
    }

    @Override
    public User findByPhone(String phone) {
        return userMapper.selectByPhone(phone);
    }

    @Override
    public void updateNickNameById(String id, String nickName) {
        userMapper.updateNickNameById(id, nickName);
    }

    @Override
    public void updateAvatar(String id, String avatar) {
        userMapper.updateAvatar(id, avatar);
    }

    @Override
    public void updateGender(String id, int gender) {
        userMapper.updateGender(id, gender);

    }
}
